package springbook.user.dao;

import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

import springbook.user.dao.mapper.UserMapper;
import springbook.user.domain.User;


public class UserDaoJdbc implements UserDao {
	private JdbcTemplate jdbcTemplate;
	private UserMapper userMapper;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public void add(final User user) {
		this.jdbcTemplate.update(
				"insert into users (id, name, password, level, login, recommend, email) values (?, ?, ?, ?, ?, ?, ?)",
				user.getId(), user.getName(), user.getPassword(),
				user.getLevel().intValue(), user.getLogin(),
				user.getRecommend(), user.getEmail());
	}

	@Override
	public User get(String id) {
		return this.jdbcTemplate.queryForObject(
				"select * from users where id = ?", new Object[] { id },
				this.userMapper);
	}

	@Override
	public List<User> getAll() {
		return this.jdbcTemplate.query(
				"select * from users order by id", this.userMapper);
	}

	@Override
	public void deleteAll() {
		this.jdbcTemplate.update("delete from users");
	}

	@Override
	public int getCount() {
		return this.jdbcTemplate.queryForInt("select count(*) from users");
	}

	@Override
	public void update(User user) {
		this.jdbcTemplate.update(
				"update users set name = ?, password = ?, level = ?, login = ?, recommend = ?, email = ? where id = ?",
				user.getName(), user.getPassword(), user.getLevel().intValue(),
				user.getLogin(), user.getRecommend(), user.getEmail(), user.getId());
	}
}
